package com.oto.server;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.caucho.hessian.server.HessianServlet;
import com.oto.api.DataService;
import com.oto.bean.Account;
import com.oto.bean.Flow;
import com.oto.bean.Pack;
import com.oto.message.Response;
import com.oto.message.ShareMessage;
import com.oto.model.FlowDO;
import com.oto.model.PackDO;
import com.oto.service.AccountService;
import com.oto.service.FlowService;
import com.oto.service.PackService;

/**
 * @author xueqiang.mi
 * @since 2011-1-9
 */
public class DataServiceImpl extends HessianServlet implements DataService {
	private static final long serialVersionUID = -1387779181032667778L;

	protected AccountService accountService;
	protected PackService packService;
	protected FlowService flowService;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
		accountService = (AccountService) ctx.getBean("accountService");
		packService = (PackService) ctx.getBean("packService");
		flowService = (FlowService) ctx.getBean("flowService");
	}

	public Response share(ShareMessage msg) {
		String userName = null; // 用于设置到pack和flow中的用户名

		// 处理account信息
		Account owner = msg.getOwner();
		if (owner != null) {
			if (accountService.get(owner.getName()) == null) {
				accountService.add(owner.getName(), owner.getTyep());
			}
			userName = owner.getName();
		} else {
			userName = "anonymous";
		}

		// 处理pack信息
		Pack p = msg.getPack();
		if (p != null) {
			if (packService.getPack(p.getName(), userName) == null) {
				packService.createPackForUser(p.getName(), userName);
			}
			// 处理pack中的flows
			PackDO pack = packService.getPack(p.getName(), userName);
			for (Flow f : p.getFlows()) {
				FlowDO flow = new FlowDO();
				flow.setName(f.getName());
				flow.setContent(f.getContent());
				flow.setPackId(pack.getId());
				flow.setOwner(userName);
				flowService.add(flow);
			}
		}

		Response resp = new Response();
		resp.setResult(Response.RST_OK);
		return resp;
	}
}
